import logging
from pathlib import Path
import urllib.parse
from rich.progress import open
import requests

class AlistConn:
    def __init__(self, host):
        self.host = host
        self.token = ""

    def get_token(self, username, password):
        data = {
            "username": username,
            "password": password,
            "authcode": "null",
        }
        headers = {"Content-Type": "application/json"}
        response = requests.post(
            self.host + "/api/admin/login",
            data=data,
            headers=headers,
        )
        if response.ok:
            self.token = response.json()["data"]["access_token"]
            return self.token
        else:
            logging.error("认证错误：" + response.text)
            return None

    def get_raw_url(self, path, password=""):
        """path:形如/a/b.txt，只能是文件，不能是目录
        私密分享需要登录才能获取，这里的password是目录的密码不是用户的密码"""
        if self.token:
            return requests.post(
                self.host + "/api/fs/get",
                data={"path": path, "password": password},
                headers={"Authorization": self.token},
            ).json()["data"]["raw_url"]
        else:
            return requests.post(
                self.host + "/api/fs/get",
                {"path": path, "password": password},
            ).json()["data"]["raw_url"]

    def upload_by_aria2(self, path, urls):
        "path:/a/b.txt"
        # post-data中的Path和Urls要注意大写
        return requests.post(
            self.host + "/api/fs/add_aria2",
            data={"Path": path, "Urls": urls},
            headers={"Authorization": self.token},
        ).json()

    def upload_local_file(self, url_path, local_path):
        with open(local_path, "rb") as file:
            return requests.put(
                self.host + "/api/fs/put",
                data=file,
                headers={
                    "Authorization": self.token,
                    "As-Task": "true",
                    "File-Path": urllib.parse.quote(url_path, encoding="utf-8"),
                },
            ).json()

    # ============一个奇怪但是可能有用的函数============
    def download_file(self, url_path, save_dir):
        "url_path以/起头，如：/shared/baidunetdisk/特性表.txt"
        save_dir = Path(save_dir)
        fileinfo_response = requests.get(
            self.host + "/api/fs/get",
            data={"path": url_path},
            headers={"Authorization": self.token},
        )
        file_info = fileinfo_response.json()["data"]
        if not file_info["is_dir"]:
            content_response = requests.get(
                self.host + "d" + url_path,
                data={"sign": file_info["sign"]},
                headers={"Authorization": self.token},
            )
            save_dir.mkdir(parents=True, exist_ok=True)
            save_dir.joinpath(file_info["name"]).write_bytes(content_response.content)
